<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script>
	/**
	*Author: Clay Liao
	*Date: 2009/11
	*Thrid party API: Yahoo Weather RSS Feed, Google AJAX Language API
	**/
	var myport;		
	var pollInterval = 60000 * 30;  //  30 minute
	var requestTimeout = 5000;  // 5 seconds	
	var yWeatherAtom = "";
	//Units for temperature (case sensitive). f: Fahrenheit and c: Celsius	
	var unit = "c";
	var temperature;	
	var zip = "TWXX0021";	
	var city = "台北市";
	var lg = "zh-TW";

	//Error message
	var ERROR_CONNECTION = "Error!"

	chrome.extension.onConnect.addListener(onPortConnect);
	function onPortConnect(port){
        if (port.name != 'y_weather') 
            return false;
        myport = port;
        port.onMessage.addListener(onMessageRecieved)
    }
	
	//google translate api
	google.load("language", "1");
	
	function onMessageRecieved(data){                
		if (data.message == "preferences") {
            localStorage.clear();
            localStorage.setItem('location', data.location);
			localStorage.setItem('zip', data.zip);
			localStorage.setItem('lg', data.lg);
			localStorage.setItem('unit', data.unit);
        }
		scheduleRequest();
    }
	
	function init() {	  
	console.log("start");	
	  window.setTimeout(startRequest, 0);
	}
	
	function scheduleRequest() {
	  window.setTimeout(startRequest, pollInterval);
	}	 
	
	// ajax stuff
	function startRequest() { 
	  //toggleStart();	  
	  var prefZip = localStorage.getItem('zip');
	  var prefCity = localStorage.getItem('location');
	  var prefLg = localStorage.getItem('lg');
	  var prefUnit = localStorage.getItem('unit');
	  if (prefUnit != null){
		unit = prefUnit;
	  }	
	  if (prefLg != null){
		lg = prefLg;
	  }		
	  if (prefZip != null || prefCity != null){		
		zip = prefZip;
		city = prefCity;
		google.language.translate(prefCity, "", lg, function(result) {
		  if (!result.error) {
			var container = document.getElementById("city");
			container.innerHTML = "[" + result.translation + "]";
		  }
		});		
	  }else{
		zip = "TWXX0021";	
		city = "台北市";
		var container = document.getElementById("city");
		container.innerHTML = "[" + city + "]";
	  }
	  
	  yWeatherAtom = "http://weather.yahooapis.com/forecastrss?p="+zip+"&u="+unit;
	  getXML(
		function() {		  
		  updateWeatherInfo();
		  //toggleStop();
		  scheduleRequest();
		},
		function() {
		  //toggleStop();
		  toggleFail();
		  scheduleRequest();
		}
	  );
	}	
	
	function getXML(onSuccess, onError) {
	  var xhr = new XMLHttpRequest();
	  var abortTimerId = window.setTimeout(function() {
		xhr.abort();
		onError();
	  }, requestTimeout);

	  function handleSuccess() {
		window.clearTimeout(abortTimerId);
		onSuccess();
	  }

	  function handleError() {
		window.clearTimeout(abortTimerId);
		onError();
	  }

	  try {
		//console.log("request...");
		xhr.onreadystatechange = function(){		
		  //console.log("readystate: " + xhr.readyState);		  
		  if (xhr.readyState == 4) {
			if (xhr.responseXML) {			  
			  var xmlDoc = xhr.responseXML;			  			  			 
			  temperature = xmlDoc.getElementsByTagName('item')[0].childNodes[11].getAttribute('temp');	 
			  w_text = xmlDoc.getElementsByTagName('item')[0].childNodes[11].getAttribute('text');		  
			  var desc = xmlDoc.getElementsByTagName('description')[1].childNodes[0].nodeValue;			  
			  var index_start = desc.indexOf('<img src=') + 10;
			  var index_end = desc.indexOf('.gif') + 4;			  
			  img_url = desc.slice(index_start, index_end);
			    
			  google.language.translate(w_text, "", lg, function(result) {
				  if (!result.error) { 
					var container = document.getElementById("status");
					container.innerHTML = result.translation;								
				  }
				});	
				
			  handleSuccess();
			  
			} else {
			  console.log("No responseXML!");
			  handleError();
			}			
		  }
		}
		
		xhr.onerror = function(error) {
		  console.log("error: " + error);		 
		  handleError();
		}

		xhr.open("GET", yWeatherAtom, true);
		xhr.send(null);
	  } catch(e) {
		//console.log("ex: " + e);
		//console.error("exception: " + e);
		handleError();
	  }
	}
	
	// ui stuff
	/*
	function toggleStart() {
	  document.getElementById("loading").style.display = "";
	}
	
	function toggleStop() {
	  document.getElementById("loading").style.display = "none";
	}
	*/
	function toggleFail() {
	  document.getElementById("status").innerHTML = ERROR_CONNECTION;
	}
	
	function updateWeatherInfo() {		  
	  document.getElementById("logo").setAttribute('src', img_url);
	  if(unit == 'f'){
		document.getElementById("temp").innerHTML = ", " + temperature + " °F";
	  }else{
		document.getElementById("temp").innerHTML = ", " + temperature + " °C";
	  }
	}
	
	function open_preferences(){
		//window.open('preferences.html');		
        chrome.tabs.create({
            url: 'preferences.html'
        })
    }
			
</script>
</head>
<body onload="init()">
  <div class="toolstrip-button" onclick="open_preferences()">
    <div id="city" style="font-weight: bold;">[City]</div>&nbsp;<div id="status">Loading...</div><div id="temp"></div>&nbsp;
	<img id="logo" src="alert.png" title="Connect Error!" />
	<!--&nbsp;<img id="loading" style="display:none;" src="ajax-loader.gif">-->
  </div>	
</body>
</html>